package com.qf.serviceimpl;

import com.qf.constant.CacheConstants;
import com.qf.constant.StrategyConstants;
import com.qf.feign.CacheFeign;
import com.qf.model.StandardSubmit;
import com.qf.service.FilterChainService;
import com.qf.util.PushMsgUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 *
 * 扣费策略
 *
 * @author Ypl
 * @version V1.0
 * @Project OctoberAndNovember
 * @Package com.qf.serviceimpl
 * @Description:
 * @Date 2022/11/10 10:49
 */
@Service(value = "fee")
@Slf4j
@SuppressWarnings("all")
public class FeeFilterServiceImpl implements FilterChainService {

    @Autowired
    CacheFeign cacheFeign;

    @Autowired
    PushMsgUtil pushMsgUtil;

    @Override
    public boolean strategy(StandardSubmit standardSubmit) {
        log.debug("【扣费策略】 开始执行");
        //设置一条消息的发送费用
        Long fee = standardSubmit.getFee();
        //根据ClientID 获取客户端
        Map map = cacheFeign.hMGet(CacheConstants.CACHE_PREFIX_CLIENT + standardSubmit.getClientID());
        //检查客户（企业是否有余额），如果没有余额就不能发了
        Integer fee1 =Integer.parseInt(String.valueOf(map.get("fee")));
        //发送的过程中判断企业的费用
        if(fee1 < standardSubmit.getFee()){
            // 发送失败 将日志存入MQ
            log.debug("【扣费策略】 因余额不足扣费失败消息发送至报告");
            pushMsgUtil.sendLog(standardSubmit, StrategyConstants.STRATEGY_ERROR_FEE);
            pushMsgUtil.pushReport(standardSubmit,StrategyConstants.STRATEGY_ERROR_FEE);
            return false;
        }
        //减少后的费用,
        map.put("fee", fee1 - standardSubmit.getFee());
//      //同步到redis
        cacheFeign.hMSet(CacheConstants.CACHE_PREFIX_CLIENT+standardSubmit.getClientID(),map);
        log.debug("【扣费策略】 执行结束");
        return true;
    }
}
